<template>
  <div class="camera">
<!--    蒙层定位无法解决-->
<!--    <div class="overlay" v-if="show"><div class="rect"></div></div>-->
    <video v-show="show" ref="video" autoplay class="camera-video"></video>
    <canvas ref="canvas" style="display: none;"></canvas>
    <div class="camera-take" @click="takePhoto"></div>
    <img :src="dataUrl" v-if="!show" @click="show = !show" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';

const video = ref<HTMLVideoElement | null>(null);
const canvas = ref<HTMLCanvasElement | null>(null);
const show = ref(true);
const dataUrl = ref('');
let stream: MediaStream | null = null;

const initCamera = async () => {
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    stream = await navigator.mediaDevices.getUserMedia({ video: true });
    if (video.value) {
      video.value.srcObject = stream;
    }
  }
};

const takePhoto = async () => {
  const context = canvas.value?.getContext('2d');
  if (context && video.value) {
    context.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height);
    dataUrl.value = canvas.value.toDataURL('image/png');
    show.value = false;
  }
};

onMounted(async () => {
  await initCamera();
});

onUnmounted(() => {
  if (stream) {
    stream.getTracks().forEach(track => track.stop()); // 关闭文件流
  }
});
</script>

<style lang="scss" scoped>
.camera {
  position: relative;
  height: 100vh;
  width: 100vw;

  &-video {
    height: 100%;
    width: 100%;
    object-fit: cover; /* 全屏显示 */
  }

  &-take {
    display: inline-block;
    position: absolute;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 60px;
    border-radius: 50%;
    z-index:99;
    background-color: white;
  }
}


.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background: transparent; /* 矩形内部透明 */
  /* 创建镂空矩形的效果 */
  .rect{
    min-width:300px;
    min-height:200px;
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
    border-top: 40vh solid rgba(0, 0, 0, 0.5); /* 设置边框颜色和宽度 */
    border-right: 40vw solid rgba(0, 0, 0, 0.5); /* 设置边框颜色和宽度 */
    border-left: 40vw solid rgba(0, 0, 0, 0.5); /* 设置边框颜色和宽度 */
    border-bottom: 60vh solid rgba(0, 0, 0, 0.5); /* 设置边框颜色和宽度 */
    background: transparent; /* 矩形内部透明 */
    z-index: 2;
  }
}
</style>